package com.jmp.autocofiguration;

import com.jmp.autocofiguration.web.filter.SecurityFilter;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author cjr
 */
@ConditionalOnClass(RequestInterceptor.class)
@Configuration
@Slf4j
public class FeignConfig implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(Objects.isNull(attributes)) {
            log.warn("Feign request attributes is null");
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        String token = getToken(request);
        if (StringUtils.isNoneBlank(token)) {
            //添加token
            requestTemplate.header(SecurityFilter.HEADER_TOKEN_FEIGN, token);
        }
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(SecurityFilter.HEADER_TOKEN_JMP);
        if (StringUtils.isBlank(token)) {// gzh ipad
            token = request.getHeader(HttpHeaders.AUTHORIZATION);
        }
        if (StringUtils.isBlank(token)) {
            token = request.getHeader(SecurityFilter.HEADER_TOKEN_FEIGN);
        }
        return token;
    }
}